<template>
  <view
    class="region-picker custom-comp"
    :class="[getDisabled && 'is-disabled', getBorder && 'is-border']"
    @click="handlePopup"
  >
    <PickerValue
      v-if="!getDisabled || showValText"
      style="height: 100%; flex: 1"
      :value-text="showValText"
      :placeholder="getPlaceholder"
      :disabled="getDisabled"
      :icon="showValText && !getDisabled ? '\ue724' : '\ue611'"
      :icon-style="
        showValText && !getDisabled
          ? {
              color: 'rgb(192, 196, 204)',
              fontSize: '40rpx',
            }
          : {
              fontSize: '30rpx',
            }
      "
      @icon-click="handleClear"
    />
  </view>

  <UniPopup ref="areaPickerPopup" type="bottom" backgroundColor="#FFF">
    <view class="areaPicker-popup">
      <view class="px-16 py-12 fz-16">{{ getPlaceholder }}</view>
      <view class="px-16 py-12 fz-14 disFlxAC">
        <template v-for="(v, index) in enableLevel" :key="index">
          <view
            class="text-overflow-1 mr-16"
            :class="[areaData[0]?.deep === index && 'active-color fw-7']"
            style="max-width: 200rpx"
            @click="handleResultClick(index)"
          >
            {{ showVal[index]?.extName || '请选择' }}
          </view>
        </template>
      </view>
      <scroll-view scroll-y style="height: 40vh">
        <template v-for="v in areaData" :key="v.id">
          <view
            class="px-16 fz-14 py-10 disFlxJS"
            :class="[showVal[v.deep]?.id === v.id && 'active-color']"
            @click="chooseAreaItem(v)"
          >
            <text>{{ v.extName }}</text>
            <text v-if="showVal[v.deep]?.id === v.id" class="ali-icon">&#xe69f;</text>
          </view>
        </template>
      </scroll-view>
    </view>
  </UniPopup>
</template>

<script setup lang="ts">
  import UniPopup from '@/uni_modules/uni-popup/components/uni-popup/uni-popup.vue';
  import { computed, getCurrentInstance, ref, watch } from 'vue';
  import { useFormItem } from '../hooks/useContext';
  import PickerValue from './PickerValue.vue';
  import type { IAreaDataResultItem } from '@/api/indexTypes';
  import { getCityData } from '../utils/getCityData';
  import { isArray } from 'lodash-es';
  import { parseFormValue } from '../hooks/useFormValues';

  const { getProps, setFormModel, formProps, component } = useFormItem({});

  const getBorder = computed(() => !formProps?.border);

  const getPlaceholder = computed(() => {
    return getProps.value.placeholder || '请选择';
  });

  const enableLevel = computed(() => Number(getProps.value.enableValue) || 4);
  const itemDefault = computed(() => parseFormValue(getProps.value.itemDefault, component) || []);

  const getDisabled = computed(() => getProps.value.disabled);

  const showVal = ref<IAreaDataResultItem[]>([]);
  const showValText = ref<string>();

  function handleClear() {
    if (showValText.value && !getDisabled.value) {
      showVal.value = [];
      showValText.value = '';
      setFormModel([]);
      __init(true);
    }
  }

  const _this = getCurrentInstance();
  function handlePopup() {
    if (getDisabled.value) return;
    (_this?.refs['areaPickerPopup'] as any).open();
  }

  const areaData = ref<IAreaDataResultItem[]>([]);
  async function getData(pid: number = 0) {
    const res = await getCityData(pid);
    areaData.value = res;
    return res;
  }

  function chooseAreaItem(item: IAreaDataResultItem) {
    showValText.value = '';
    showVal.value = showVal.value.slice(0, item.deep);
    showVal.value[item.deep] = item;

    if (showVal.value.length === enableLevel.value) {
      showValText.value = showVal.value.map((v) => v.extName).join('');
      setFormModel(showVal.value.map((v) => v.id).join(','));
      (_this?.refs['areaPickerPopup'] as any).close();
    } else {
      getData(item.id);
    }
  }

  function handleResultClick(index: number) {
    const valItem = showVal.value[index];
    if (valItem && valItem.pid !== areaData.value[0].pid) {
      getData(valItem.pid);
    }
  }

  function getIndex(data: IAreaDataResultItem[], id?: number) {
    let index = data.findIndex((v) => v.id == id);
    return index === -1 ? 0 : index;
  }

  async function __init(isClear: boolean = false) {
    let modelValue = getProps.value.modelValue || [];
    modelValue = isArray(modelValue) ? modelValue : modelValue.split(',');
    showVal.value = [];

    if (modelValue.length || itemDefault.value.length) {
      const vals = modelValue.length ? modelValue : itemDefault.value;
      let lastData: IAreaDataResultItem[] = [];
      for (let index = 0; index < enableLevel.value; index++) {

        const data = await getData(index > 0 ? Number(vals[index - 1]) : 0);
        if (!vals[index]) continue;
        const id = Number(vals[index]);
        const dataIndex = getIndex(data, id);
        lastData = data;
        if (!isClear || itemDefault.value.length) {
          showVal.value.push(data[dataIndex]);
        }
      }
    } else {
      await getData(0);
    }

    if (showVal.value.length && modelValue.length) {
      showValText.value = showVal.value.map((v) => v.extName).join('');
    }
  }

  watch(enableLevel, () => __init(), {
    immediate: true,
  });
</script>

<style lang="scss" scoped>
  @import '../styles/form.scss';
  .areaPicker-popup {
    color: #333;
  }
  .active-color {
    color: #2878ff;
  }
</style>
